<template>
  <div class="add-book">
    <h2>贡献图书</h2>
    <form @submit.prevent="submitBook">
      <input v-model="book.title" placeholder="书名" required>
      <input v-model="book.author" placeholder="作者" required>
      <input v-model="book.isbn" placeholder="ISBN" required>
      <input type="file" @change="handleCoverUpload" accept="image/*">
      <button type="submit">贡献</button>
    </form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'AddBook',
  data() {
    return {
      book: {
        title: '',
        author: '',
        isbn: ''
      },
      coverFile: null
    }
  },
  methods: {
    ...mapActions(['addBook', 'fetchBooks']),
    handleCoverUpload(event) {
      this.coverFile = event.target.files[0]
    },
    async submitBook() {
      try {
        console.log('Submitting book:', this.book)
        const formData = new FormData()
        
        // 将书籍信息转换为 JSON 字符串
        const bookInfo = JSON.stringify({
          title: this.book.title,
          author: this.book.author,
          isbn: this.book.isbn
        })
        
        formData.append('book', bookInfo)
        
        // 如果有封面图片，添加到 formData
        if (this.coverFile) {
          formData.append('file', this.coverFile)
        }

        console.log('FormData:', formData)
        const response = await this.addBook(formData)
        console.log('Add book response:', response)
        await this.fetchBooks({ page: 0 }) // 重新获取第一页的图书列表
        this.book = { title: '', author: '', isbn: '' }
        this.coverFile = null
        this.$router.push('/')
      } catch (error) {
        console.error('Error adding book:', error)
      }
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
</style>